import React, { useEffect } from 'react';
import { Row, Button, Collapse, Divider, Tag, message, Spin, Empty, Popconfirm } from 'antd';
import { history } from 'umi'
import moment from 'moment';
import { useRequest } from '@/hooks';
import { DividerContainer } from '@/molecules';
import authHelper from '@/utils/auth/helper';
import { ChannelListItem, Icon, InviteDetail } from '../components';
import {
    ChannelForm,
    ChannelSetPopover,
    AccountTable,
    AccountModal,
    ExternalAccountModal,
    CompanyModal,
    CustomChannelModal
} from './containers';
import { getChannelList, deleteHuntingChannel, deleteCustomChannel } from './service';
import styles from './index.less';

const { checkCode } = authHelper;
const { Panel } = Collapse;

const CHANNEL = {
    INTERNAL: 1,
    EXTERNAL: 2,
    HUNTING: 3
};

const ChannelTag = ({ channelStatus, openStatus }) => {
    const tagData = React.useMemo(() => {
        // 已开通
        if (openStatus === 3) {
            const ret = [{ classes: styles.tagOpenStyle, text: '已开通' }];
            // 禁用
            if (channelStatus === 0) {
                ret.push({ classes: null, text: '禁用' });
            } else {
                ret.push({ classes: styles.tagOpenStyle, text: '启用' });
            }
            return ret;
        }
        // 未开通
        if (openStatus === 1) {
            return [{ classes: styles.tagUnOpenStyle, text: '未开通' }];
        }
        // 开通中
        if (openStatus === 2) {
            return [{ classes: styles.tagOpeningStyle, text: '开通中' }];
        }
        return [];
    }, [openStatus, channelStatus]);
    return (
        <div style={{ display: 'inline-flex', marginLeft: 8 }}>
            {tagData.map(({ text, classes } = {}) => Boolean(text) && <Tag className={classes}>{text}</Tag>)}
        </div>
    );
};

const Channel = () => {
    const [nowType, setNowType] = React.useState('all');
    const [nowParams, setNowParams] = React.useState(null);
    // 获取渠道列表
    const { data: channelData, loading, run: fetchList } = useRequest(getChannelList, {
        manual: true,
        initialData: { internalChannel: [], externalChannel: [], headhuntingChannel: [] },
        formatResult: result => {
            const { code, data, msg } = result;
            if (code === 10000) {
                if (nowType === 'all') {
                    return data;
                }
                if (nowType === CHANNEL.INTERNAL) {
                    return {
                        ...channelData,
                        internalChannel: data?.internalChannel || []
                    };
                }
                if (nowType === CHANNEL.EXTERNAL) {
                    return {
                        ...channelData,
                        externalChannel: data?.externalChannel || []
                    };
                }
                if (nowType === CHANNEL.HUNTING) {
                    return {
                        ...channelData,
                        headhuntingChannel: data?.headhuntingChannel || []
                    };
                }
            }
            message.error(msg);
            return { internalChannel: [], externalChannel: [], headhuntingChannel: [] };
        }
    });

    const handleDelete = id => {
        if (id) {
            deleteHuntingChannel(id).then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success('删除成功');
                    setNowType(3);
                    fetchList({
                        ...(nowParams?.[3] || null),
                        channelType: 3
                    });
                } else {
                    message.error(msg);
                }
            });
        }
    };

    const handleSearch = (data, type) => {
        setNowType(type);
        setNowParams({
            ...nowParams,
            [type]: data
        });
        fetchList({
            ...data,
            channelType: type
        });
    };

    const handleRefresh = type => {
        setNowType(type);
        fetchList({
            ...nowParams?.[type],
            channelType: type
        });
    };

    useEffect(() => {
        fetchList();
    }, []);

    const handleGoToRecord = channelCodes => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/channel/history',
            query: {
                channelCodes,
                channelType: '3'
            }
        });
    };

    const renderTime = t => (t ? moment(t).format('YYYY-MM-DD HH:mm') : t);

    const getLogoUrl = item => {
        const { logoUrl, recruitChannelLogoFile = [] } = item;
        if (logoUrl) {
            return logoUrl;
        }
        if (recruitChannelLogoFile.length > 0) {
            return recruitChannelLogoFile[0]?.url;
        }
        return '';
    };

    const renderEmails = emails => {
        if (!emails) {
            return '';
        }
        const arr = emails.split(',');
        return arr.map((item, index) => {
            const tempKey = index;
            return (
                <span style={{ display: 'inline-block' }} key={tempKey}>
                    {item}
                    {index < arr.length - 1 ? '；' : ''}
                </span>
            );
        });
    };

    const headerStyle = { fontSize: 14, color: 'rgba(0, 0, 0, 0.65)', fontWeight: 500 };
    const { run: runDeleteCustomChannel } = useRequest(deleteCustomChannel, {
        manual: true,
        onSuccess: () => {
            message.success('删除成功');
            fetchList({
                ...(nowParams?.[nowType] || null),
                channelType: nowType
            });
        }
    });
    const renderCustomRowBtn = React.useCallback(
        (item, type) => (
            <DividerContainer>
                {true && (
                    <CustomChannelModal
                        data={item}
                        onSuccess={() => handleRefresh(type)}
                        channelType={type}
                        renderTrigger={({ onClick }) => (
                            <Icon title="编辑渠道" type="listfunction_edit_icon_default" onClick={onClick} />
                        )}
                    ></CustomChannelModal>
                )}
                {true && (
                    <Popconfirm
                        title="确定删除该渠道吗？"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => {
                            setNowType(type);
                            runDeleteCustomChannel(item.id);
                        }}
                    >
                        <Icon title="删除" type="DeleteIcon" />
                    </Popconfirm>
                )}
            </DividerContainer>
        ),
        []
    );

    return (
        <div className={styles.channelWrap}>
            <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 16 }}>
                <span style={{ fontSize: 16, color: 'rgba(0, 0, 0, 0.85)', fontWeight: 600 }}>招聘渠道</span>
                <DividerContainer>
                    {checkCode('office:recruitment:channel:statistics') && (
                        <Button
                            type="primary"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/recruitment/channel/history'
                                });
                            }}
                        >
                            全部统计
                        </Button>
                    )}
                    <Button
                        onClick={() => {
                            history.push({
                                pathname: '/office/personnelManagement/recruitment/channel/operate'
                            });
                        }}
                    >
                        操作记录
                    </Button>
                </DividerContainer>
            </Row>
            <Collapse defaultActiveKey={['1']} expandIconPosition="right">
                <Panel header={<span style={{ ...headerStyle, color: 'rgba(0,0,0,0.85)' }}>内部渠道</span>} key="1">
                    <Row type="flex" justify="space-between" style={{ marginBottom: 16 }}>
                        <div style={{ flex: 1 }}>
                            <ChannelForm type={CHANNEL.INTERNAL} onSubmit={handleSearch} />
                        </div>
                        <div style={{ display: 'flex', height: 40, alignItems: 'center' }}>
                            <CustomChannelModal
                                onSuccess={() => handleRefresh(CHANNEL.INTERNAL)}
                                channelType={CHANNEL.INTERNAL}
                                renderTrigger={({ onClick }) => (
                                    <Button ghost type="primary" onClick={onClick}>
                                        + 新增
                                    </Button>
                                )}
                            ></CustomChannelModal>
                        </div>
                    </Row>
                    <Spin spinning={loading && (nowType === 'all' || nowType === CHANNEL.INTERNAL)}>
                        {channelData?.internalChannel?.length === 0 ? (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: '50px 0' }} />
                        ) : (
                            channelData?.internalChannel?.map(item => (
                                <ChannelListItem
                                    key={item.id}
                                    avatar={getLogoUrl(item)}
                                    disabled={item.channelStatus === 0}
                                    title={
                                        <div style={headerStyle}>
                                            {item.channelName}
                                            <ChannelTag {...item} />
                                        </div>
                                    }
                                    titleExtra={
                                        item.openStatus === 3 ? (
                                            <DividerContainer>
                                                {checkCode('office:recruitment:setting:channel:setting') && (
                                                    <ChannelSetPopover
                                                        type={CHANNEL.INTERNAL}
                                                        data={item}
                                                        onSuccess={handleRefresh}
                                                    >
                                                        <Icon title="设置" type="shezhi" onClick={() => {}} />
                                                    </ChannelSetPopover>
                                                )}
                                                {checkCode('office:recruitment:channel:statistics') && (
                                                    <Icon
                                                        title="统计记录"
                                                        type="chakanfabuxinxi"
                                                        onClick={() => handleGoToRecord(item.channelCode)}
                                                    />
                                                )}
                                            </DividerContainer>
                                        ) : (
                                            renderCustomRowBtn(item, CHANNEL.INTERNAL)
                                        )
                                    }
                                />
                            ))
                        )}
                    </Spin>
                </Panel>
            </Collapse>
            <Collapse
                defaultActiveKey={['1']}
                expandIconPosition="right"
                className={styles.outWrap}
                style={{ marginTop: 24 }}
            >
                <Panel header={<span style={{ ...headerStyle, color: 'rgba(0,0,0,0.85)' }}>外部渠道</span>} key="1">
                    <Collapse
                        defaultActiveKey={['1']}
                        bordered={false}
                        className={styles.custom}
                        expandIconPosition="right"
                    >
                        <Panel header={<span style={headerStyle}>招聘网站</span>} key="1">
                            <Row type="flex" justify="space-between" style={{ marginBottom: 16 }}>
                                <div style={{ flex: 1 }}>
                                    <ChannelForm type={CHANNEL.EXTERNAL} onSubmit={handleSearch} />
                                </div>
                                <div style={{ display: 'flex', height: 40, alignItems: 'center' }}>
                                    <CustomChannelModal
                                        onSuccess={() => handleRefresh(CHANNEL.EXTERNAL)}
                                        channelType={CHANNEL.EXTERNAL}
                                        renderTrigger={({ onClick }) => (
                                            <Button ghost type="primary" onClick={onClick}>
                                                + 新增
                                            </Button>
                                        )}
                                    ></CustomChannelModal>
                                </div>
                            </Row>
                            <Spin spinning={loading && (nowType === 'all' || nowType === CHANNEL.EXTERNAL)}>
                                {channelData?.externalChannel?.length === 0 ? (
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: '50px 0' }} />
                                ) : (
                                    channelData?.externalChannel?.map(item => (
                                        <ChannelListItem
                                            key={item.id}
                                            avatar={getLogoUrl(item)}
                                            disabled={item.channelStatus === 0}
                                            title={
                                                <div style={headerStyle}>
                                                    {item.channelName}
                                                    <ChannelTag {...item} />
                                                </div>
                                            }
                                            titleExtra={
                                                item.openStatus === 3 ? (
                                                    <DividerContainer>
                                                        {checkCode('office:recruitment:setting:channel:setting') && (
                                                            <ChannelSetPopover
                                                                type={CHANNEL.EXTERNAL}
                                                                data={item}
                                                                onSuccess={handleRefresh}
                                                            >
                                                                <Icon title="设置" type="shezhi" onClick={() => {}} />
                                                            </ChannelSetPopover>
                                                        )}{' '}
                                                        {checkCode(
                                                            'office:recruitment:setting:channel:account:create'
                                                        ) && (
                                                            <AccountModal
                                                                channelCode={item.channelCode}
                                                                onSuccess={handleRefresh}
                                                            >
                                                                <Icon
                                                                    title="新增渠道账号"
                                                                    type="xinzengqudaozhanghao"
                                                                    onClick={() => {}}
                                                                />
                                                            </AccountModal>
                                                        )}
                                                        {checkCode('office:recruitment:setting:channel:update') && (
                                                            <ExternalAccountModal
                                                                data={item}
                                                                onSuccess={() => handleRefresh(2)}
                                                            >
                                                                <Icon
                                                                    title="编辑渠道"
                                                                    type="listfunction_edit_icon_default"
                                                                    onClick={() => {}}
                                                                />
                                                            </ExternalAccountModal>
                                                        )}
                                                        {checkCode('office:recruitment:channel:statistics') && (
                                                            <Icon
                                                                title="统计记录"
                                                                type="chakanfabuxinxi"
                                                                onClick={() => handleGoToRecord(item.channelCode)}
                                                            />
                                                        )}
                                                    </DividerContainer>
                                                ) : (
                                                    renderCustomRowBtn(item, CHANNEL.EXTERNAL)
                                                )
                                            }
                                            content={
                                                item.openStatus === 3 && (
                                                    <InviteDetail
                                                        keyStyle={{ color: 'rgba(0,0,0,0.65)', fontWeight: 400 }}
                                                        valueStyle={{ color: 'rgba(0,0,0,0.65)', fontWeight: 400 }}
                                                        style={{ marginBottom: 0 }}
                                                        dataSource={[
                                                            {
                                                                key: '发送简历邮箱',
                                                                value: renderEmails(item.channelEmail)
                                                            }
                                                        ]}
                                                    />
                                                )
                                                // <div>发送简历邮箱：{item.channelEmail}</div>
                                            }
                                            footer={
                                                item.openStatus === 3 &&
                                                checkCode('office:recruitment:setting:channel:account') && (
                                                    <AccountTable
                                                        channelCode={item.channelCode}
                                                        loginLink={item?.loginLink}
                                                        data={item?.channelAccountDetailVOList}
                                                        onRefresh={handleRefresh}
                                                    />
                                                )
                                            }
                                        />
                                    ))
                                )}
                            </Spin>
                        </Panel>
                    </Collapse>
                    <Divider style={{ margin: '12px 0' }} />
                    <Collapse
                        defaultActiveKey={['1']}
                        bordered={false}
                        className={styles.custom}
                        expandIconPosition="right"
                    >
                        <Panel header={<span style={headerStyle}>猎头公司</span>} key="1">
                            <Row type="flex" justify="space-between" style={{ marginBottom: 16 }}>
                                <div style={{ flex: 1 }}>
                                    <ChannelForm type={CHANNEL.HUNTING} onSubmit={handleSearch} />
                                </div>
                                <div style={{ display: 'flex', height: 40, alignItems: 'center' }}>
                                    {checkCode('office:recruitment:setting:channel:template') && (
                                        <Button
                                            style={{ marginRight: 12 }}
                                            onClick={() => {
                                                history.push({
                                                    pathname:
                                                        '/office/personnelManagement/recruitment/setting/email/template'
                                                });
                                            }}
                                        >
                                            发送模板设置
                                        </Button>
                                    )}
                                    {checkCode('office:recruitment:setting:channel:create') && (
                                        <CompanyModal onSuccess={() => handleRefresh(3)}>
                                            <Button ghost type="primary">
                                                + 新增
                                            </Button>
                                        </CompanyModal>
                                    )}
                                </div>
                            </Row>
                            <Spin spinning={loading && (nowType === 'all' || nowType === CHANNEL.HUNTING)}>
                                {channelData?.headhuntingChannel?.length === 0 ? (
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: '50px 0' }} />
                                ) : (
                                    channelData?.headhuntingChannel?.map(item => (
                                        <ChannelListItem
                                            key={item.id}
                                            avatar={getLogoUrl(item)}
                                            disabled={item.channelStatus === 0}
                                            title={
                                                <div style={headerStyle}>
                                                    {item.channelName}
                                                    <ChannelTag {...item} />
                                                </div>
                                            }
                                            titleExtra={
                                                <DividerContainer>
                                                    {checkCode('office:recruitment:setting:channel:setting') && (
                                                        <ChannelSetPopover
                                                            type={CHANNEL.HUNTING}
                                                            data={item}
                                                            onSuccess={handleRefresh}
                                                        >
                                                            <Icon title="设置" type="shezhi" onClick={() => {}} />
                                                        </ChannelSetPopover>
                                                    )}
                                                    {checkCode('office:recruitment:setting:channel:update') && (
                                                        <CompanyModal data={item} onSuccess={() => handleRefresh(3)}>
                                                            <Icon
                                                                title="编辑猎头公司"
                                                                type="listfunction_edit_icon_default"
                                                                onClick={() => {}}
                                                            />
                                                        </CompanyModal>
                                                    )}
                                                    {checkCode('office:recruitment:setting:channel:delete') && (
                                                        <Popconfirm
                                                            title="确定删除该渠道吗？"
                                                            okText="确定"
                                                            cancelText="取消"
                                                            onConfirm={() => handleDelete(item?.id)}
                                                        >
                                                            <Icon title="删除" type="DeleteIcon" onClick={() => {}} />
                                                        </Popconfirm>
                                                    )}
                                                    {checkCode('office:recruitment:channel:statistics') && (
                                                        <Icon
                                                            title="统计记录"
                                                            type="chakanfabuxinxi"
                                                            onClick={() => handleGoToRecord(item.channelCode)}
                                                        />
                                                    )}
                                                </DividerContainer>
                                            }
                                            content={
                                                <InviteDetail
                                                    keyStyle={{ color: 'rgba(0,0,0,0.65)', fontWeight: 400 }}
                                                    valueStyle={{ color: 'rgba(0,0,0,0.65)', fontWeight: 400 }}
                                                    style={{ marginBottom: 0 }}
                                                    dataSource={[
                                                        {
                                                            key: '接收需求邮箱',
                                                            value: renderEmails(item.acceptRecruitEmail)
                                                        },
                                                        {
                                                            key: '发送简历邮箱',
                                                            value: renderEmails(item.channelEmail)
                                                        },
                                                        {
                                                            key: '授权用户',
                                                            value: item.channelAccountAuthVOList
                                                                ?.map(bar => bar.authEmployeeName)
                                                                ?.join(';')
                                                        },
                                                        {
                                                            key: '联系人姓名',
                                                            value: item.channelLinkName
                                                        },
                                                        {
                                                            key: '联系人电话',
                                                            value: item.channelLinkTel
                                                        },
                                                        {
                                                            key: '创建时间',
                                                            value: renderTime(item?.createTime)
                                                        }
                                                    ]}
                                                />
                                            }
                                        />
                                    ))
                                )}
                            </Spin>
                        </Panel>
                    </Collapse>
                </Panel>
            </Collapse>
        </div>
    );
};

export default Channel;
